import './style.less';

import * as R from 'ramda';

import { Button, Form, Input, message } from 'antd';
import React, { useCallback } from 'react';

import Cookies from 'js-cookie';
import Icon from '../../components/Icon';
import { cssClass } from '@/utils/common';
import { register } from '@/service/auth';
import { unResWrapper } from '../../utils/common';
import { useHistory } from 'react-router-dom';
import { useRequest } from 'ahooks';

const registerCls = cssClass('register');

const Register = () => {
  const [form] = Form.useForm();
  const history = useHistory();
  const { run, loading } = useRequest(
    (data) => {
      delete data.confirmPassword;
      return unResWrapper(register)(data);
    },
    {
      manual: true,
      throwOnError: true,
    },
  );

  const submit = useCallback(() => {
    form
      .validateFields()
      .then(run)
      .then(() => {
        message.success('注册成功', 1, () => {
          // Cookies.set('token', token);
          history.replace('/login');
        });
      });
  }, [run, form, history]);

  const enterHandle = R.when(R.propEq('keyCode', 13), submit);

  return (
    <div className={registerCls('wrap')}>
      <h2>欢迎来到{new Date().getFullYear()}</h2>
      <Form className={registerCls('form')} size="large" form={form}>
        <Form.Item
          name="username"
          rules={[{ required: true, message: '用户名不能为空' }]}
        >
          <Input
            prefix={<Icon type="user-outlined" />}
            placeholder="必填，请输入用户名"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '密码不能为空' }]}
        >
          <Input.Password
            prefix={<Icon type="lock-outlined" />}
            placeholder="必填，请输入密码"
            onKeyDown={enterHandle}
          />
        </Form.Item>
        <Form.Item
          name="confirmPassword"
          rules={[
            { required: true, message: '确认密码不能为空' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次密码不一致'));
              },
            }),
          ]}
        >
          <Input.Password
            prefix={<Icon type="lock-outlined" />}
            placeholder="必填，请再次输入密码"
            onKeyDown={enterHandle}
          />
        </Form.Item>
        <Form.Item
          name="email"
          rules={[{ type: 'email', message: '邮箱格式不正确' }]}
        >
          <Input
            prefix={<Icon type="mail-outlined" />}
            placeholder="选填，请输入邮箱地址"
            onKeyDown={enterHandle}
          />
        </Form.Item>
        <Form.Item
          name="phone"
          rules={[
            { pattern: /1[3456789]\d{9}/, message: '手机号码格式不正确' },
          ]}
        >
          <Input
            prefix={<Icon type="mobile-outlined" />}
            placeholder="选填，请输入手机号码"
            onKeyDown={enterHandle}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" block onClick={submit} loading={loading}>
            注册
          </Button>
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            block
            ghost
            onClick={() => history.replace('/login')}
          >
            去登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Register;
